<script setup>
import { ref } from 'vue'
import CategoryComponents from '@/views/article/components/CategoryComponents.vue'
import {
  articleGetInofService,
  articlePublishService,
  articleUpInfoService
} from '@/api/article.js'
import { Plus } from '@element-plus/icons-vue'
import { baseURL } from '@/utils/request'

import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
const drawer = ref(false)
const data = ref({
  id: '',
  title: '',
  cate_id: '',
  content: '',
  cover_img: '',
  state: ''
})
const formModel = ref({ ...data.value })
const loading = ref(false)

async function urlToFile(
  url,
  fileName = 'image.png',
  mimeType = 'image/png'
) {
  const response = await fetch(url)
  const blob = await response.blob()
  return new File([blob], fileName, {
    type: mimeType
  })
}
//提供open方法暴露出去让其他组件能打开抽屉
const imageUrl = ref('')
const textRef = ref()
const open = async (row) => {
  drawer.value = true
  if (row.id) {
    const {
      data: { data }
    } = await articleGetInofService(row.id)
    imageUrl.value = baseURL + data.cover_img
    formModel.value = data
    formModel.value.cover_img = await urlToFile(
      formModel.value.cover_img
    )
  } else {
    formModel.value = data.value
    imageUrl.value = ''
    textRef.value.setHTML('')
  }
}
//上传成功的钩子
const onAvatarSuccess = () => {}
//文件改变时的钩子
const onChange = (uploadFile) => {
  imageUrl.value = URL.createObjectURL(
    uploadFile.raw
  )
  formModel.value.cover_img = uploadFile.raw
}

//添加或者编辑
const emit = defineEmits(['success'])
const onAddArticle = async (str) => {
  loading.value = true
  formModel.value.state = str
  const fd = new FormData()
  for (let key in formModel.value) {
    fd.append(key, formModel.value[key])
  }
  if (!formModel.value.id) {
    await articlePublishService(fd)
    emit('success', 'add')
  } else {
    console.log(fd)
    await articleUpInfoService(fd)
    emit('success', 'up')
  }
  ElMessage.success('操作成功！')
  drawer.value = false
  loading.value = false
}

defineExpose({
  open
})
</script>
<template>
  <el-drawer
    v-model="drawer"
    :title="formModel.id ? '编辑' : '添加'"
  >
    <el-form
      :model="formModel"
      ref="formRef"
      label-width="100px"
      v-loading="loading"
    >
      <el-form-item label="文章标题" prop="title">
        <el-input
          v-model="formModel.title"
          placeholder="请输入标题"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="文章分类"
        prop="cate_id"
      >
        <CategoryComponents
          v-model="formModel.cate_id"
          width="100%"
        ></CategoryComponents>
      </el-form-item>
      <el-form-item
        label="文章封面"
        prop="cover_img"
      >
        <el-upload
          class="avatar-uploader"
          :show-file-list="false"
          :on-success="onAvatarSuccess"
          :auto-upload="false"
          :on-change="onChange"
        >
          <img
            v-if="imageUrl"
            :src="imageUrl"
            class="avatar"
          />
          <el-icon
            v-else
            class="avatar-uploader-icon"
          >
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item
        label="文章内容"
        prop="content"
      >
        <div class="editor">
          <div class="editor">
            <quill-editor
              theme="snow"
              v-model:content="formModel.content"
              contentType="html"
              ref="textRef"
            >
            </quill-editor>
          </div>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="onAddArticle('已发布')"
          >发布</el-button
        >
        <el-button
          type="info"
          @click="onAddArticle('草稿')"
          >草稿</el-button
        >
      </el-form-item>
    </el-form>
  </el-drawer>
</template>
<style scoped>
.avatar {
  width: 200px;
}

.editor {
  width: 100%;

  :deep(.ql-editor) {
    min-height: 200px;
  }
}
</style>
